/*
 * Copyright 2012 Dominik.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package cz.muni.fi.PA165.musiclibraryweb.album;

import cz.muni.fi.PA165.musiclibraryapi.dto.AlbumDTOInterface;
import cz.muni.fi.PA165.musiclibraryapi.dto.SongDTOInterface;
import cz.muni.fi.PA165.musiclibraryapi.services.AlbumService;
import cz.muni.fi.PA165.musiclibraryapi.services.SongService;
import cz.muni.fi.PA165.musiclibrarybackend.dto.AlbumDTO;
import cz.muni.fi.PA165.musiclibraryweb.ForAdminBookmarkableLink;
import cz.muni.fi.PA165.musiclibraryweb.ForAdminLink;
import cz.muni.fi.PA165.musiclibraryweb.HomePage;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import org.apache.wicket.authroles.authorization.strategies.role.annotations.AuthorizeInstantiation;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.image.NonCachingImage;
import org.apache.wicket.markup.html.link.BookmarkablePageLink;
import org.apache.wicket.markup.html.link.Link;
import org.apache.wicket.markup.html.list.AbstractItem;
import org.apache.wicket.markup.repeater.RepeatingView;
import org.apache.wicket.request.mapper.parameter.PageParameters;
import org.apache.wicket.spring.injection.annot.SpringBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 *
 * @author Dominik
 */

@AuthorizeInstantiation({"USER", "ADMIN"})
public class AlbumPage extends HomePage implements Serializable {

    @SpringBean
    private AlbumService service;
    private Label errorMessage;

    public AlbumPage(final PageParameters parameters) {
        this(parameters, null);
    }

    public AlbumPage(final PageParameters parameters, Label label) {
        super(parameters);
        add(new BookmarkablePageLink("albumView", AlbumPage.class));

        BookmarkablePageLink bookmarkLink = new ForAdminBookmarkableLink("albumAdd", AddAlbumPage.class);

        add(bookmarkLink);        

        List<AlbumDTOInterface> albums;
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        service = context.getBean(AlbumService.class);
        final SongService songService = context.getBean(SongService.class);

        if (service != null) {
            albums = service.getAllAlbums();
        } else {
            albums = new ArrayList<AlbumDTOInterface>();
        }

        if (label == null) {
            errorMessage = new Label("error", "");
            errorMessage.setVisible(false);
        } else {
            errorMessage = label;
            errorMessage.setVisible(true);
        }
        add(errorMessage);

        RepeatingView repeating = new RepeatingView("repeating");
        add(repeating);
        for (AlbumDTOInterface a : albums) {
            AbstractItem item = new AbstractItem(repeating.newChildId());

            repeating.add(item);

            final AlbumDTO albumFinal = new AlbumDTO();
            albumFinal.setName(a.getName());
            albumFinal.setId(a.getId());
            albumFinal.setComment(a.getComment());
            albumFinal.setReleaseDate(a.getReleaseDate());

            final Link editLink = new ForAdminLink("edit") {
                @Override
                public void onClick() {
                    AddAlbumPage addAlbumPage = new AddAlbumPage(parameters, albumFinal);
                    setResponsePage(addAlbumPage);
                }
            };

            item.add(editLink);
            final Link deleteLink = new ForAdminLink("delete") {
                @Override
                public void onClick() {
                    AlbumPage albumPage = new AlbumPage(parameters);
                    boolean exist = false;
                    for (SongDTOInterface s : songService.getAllSongs()) {
                        if ((s.getAlbum().equals(albumFinal))) {
                            albumPage = new AlbumPage(parameters,
                                    new Label("error", "Album " + albumFinal.getName()
                                    + ", is still used by song " + s.getName() + "."));
                            exist = true;
                            break;
                        }
                    }
                    if (!exist) {
                        try {
                            service.deleteAlbum(albumFinal);
                            albumPage = new AlbumPage(parameters);
                        } catch (Exception exception) {
                            setResponsePage(new AlbumPage(parameters,
                                    new Label("error", "Database error!")));
                        }
                    }

                    setResponsePage(albumPage);
                }
            };

            item.add(deleteLink);

            item.add(new Label("name", a.getName()));
            if (a.getReleaseDate() == null){
                item.add(new Label("date", ""));
            }
            else{
                item.add(new Label("date", String.valueOf(a.getReleaseDate())));
            }
            ImageTransform imageTransform = new ImageTransform();
            imageTransform.setImageInBytes(a.getAlbumArt());
            item.add(new NonCachingImage("albumArt", imageTransform));
            item.add(new Label("comment", a.getComment()));
        }
    }
}
